import fs from 'fs'
import path from 'path'
import os from 'os'
import EventEmitter from 'events'
class LocalFilesService extends EventEmitter {
    static instance = null

    static getInstance() {
        if (!LocalFilesService.instance) {
            LocalFilesService.instance = new LocalFilesService()
        }
        return LocalFilesService.instance
    }
    constructor() {
        super()
        if (LocalFilesService.instance) {
            return LocalFilesService.instance
        }
        LocalFilesService.instance = this
    }
    // 获取用户主目录
    getHomeDir() {
        return os.homedir()
    }
    // 获取文件列表
    async getFileList({dirPath}) {
        try {
            // 如果没有传入路径，则返回根目录
            if (!dirPath) {
                dirPath = process.platform === 'win32' 
                    ? path.parse(os.homedir()).root 
                    : '/';
            }
            // 对于驱动器的特殊处理
            else if (process.platform === 'win32' && dirPath.match(/^[A-Za-z]:$/)) {
                dirPath = `${dirPath}\\`;
            }
            const fullDirPath = path.normalize(dirPath);
            const files = await fs.promises.readdir(fullDirPath);
            const fileList = [];
            
            for (const file of files) {
                try {
                    const fullPath = path.join(fullDirPath, file);
                    const stats = await fs.promises.stat(fullPath);
                    fileList.push({
                        name: file,
                        isDirectory: stats.isDirectory(),
                        size: stats.size,
                        modifyTime: stats.mtime,
                        fullPath,
                        type: stats.isDirectory() ? 'directory' : 'file'
                    });
                } catch (err) {
                    console.log(`跳过无权限文件: ${file}`);
                    continue;
                }
            }
            
            this.emit('list-success', { path: fullDirPath, files: fileList });
            return fileList;
        } catch (error) {
            this.emit('error', { type: 'list', error: error.message });
            throw new Error(`读取目录失败: ${error.message}`);
        }
    }
    // 获取驱动器列表 (Windows)
    async getDrives() {   
        if (process.platform === 'win32') {
            try {
                const drives = []
                // 检查从 A 到 Z 的所有可能驱动器
                for (let i = 65; i <= 90; i++) {
                    const driveLetter = String.fromCharCode(i)
                    const drivePath = `${driveLetter}:\\`
                    try {
                        await fs.promises.access(drivePath)
                        drives.push({
                            name: `${driveLetter}:`,
                            fullPath: drivePath,
                            type: 'drive',
                            isDirectory: true
                        })
                    } catch {}
                }
                this.emit('drives-list', {list:drives,path:"\\"})
                return drives
            } catch (error) {
                this.emit('error', { type: 'drives', error: error.message })
                throw error
            }
        } else {
            // 对于非 Windows 系统，返回根目录
            return [{
                name: '/',
                fullPath: '/',
                type: 'drive',
                isDirectory: true
            }]
        }
    }
    // 检查文件/目录是否存在
    async exists(path) {
        try {
            await fs.promises.access(path)
            return true
        } catch {
            return false
        }
    }

    // 创建目录
    async createDirectory(dirPath) {
        try {
            await fs.promises.mkdir(dirPath, { recursive: true })
            this.emit('directory-created', dirPath)
            return true
        } catch (error) {
            this.emit('error', { type: 'create-directory', error: error.message })
            throw new Error(`创建目录失败: ${error.message}`)
        }
    }

    // 删除文件或目录
    async delete(filePath) {
        try {
            const stats = await fs.promises.stat(filePath)
            if (stats.isDirectory()) {
                await fs.promises.rm(filePath, { recursive: true, force: true })
            } else {
                await fs.promises.unlink(filePath)
            }
            this.emit('delete-success', filePath)
            return true
        } catch (error) {
            this.emit('error', { type: 'delete', error: error.message })
            throw new Error(`删除失败: ${error.message}`)
        }
    }

    // 重命名文件或目录
    async rename(oldPath, newPath) {
        try {
            await fs.promises.rename(oldPath, newPath)
            this.emit('rename-success', { oldPath, newPath })
            return true
        } catch (error) {
            this.emit('error', { type: 'rename', error: error.message })
            throw new Error(`重命名失败: ${error.message}`)
        }
    }
}

export default LocalFilesService.getInstance() 